import { ref } from 'vue'
// @ts-ignore
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'

import { goto } from "./goto"
import { TaToast } from "./script/tools"
import { TaDataUser } from "./data/user"
import { TaAbortPosts } from "./script/ajax"

// 基础混入器，包含常用方法
export const TaMixinDefault = {
	data() {
		return { goto: goto }
	},
	methods: {
		// 解析商品规格
		showSpec(rule: string = '') {
			let names: any[] = []
			rule.split(';;').map((v: string) => names.push(v.split('::').pop()))
			return names.join(' ')
		},
		// 解析规则链接
		parseUrl(rule: string = '') {
			console.log('ParseUrl: ', rule)
			let attr = rule.split('#')
			if (attr.length < 3) return 0
			if (attr[0] === '商品详情') {
				return goto.goods(attr[1])
			}
			if (attr[0] === '商品分类') {
				return goto.cate(attr[1])
			}
		},
	}
}

// 用户登录状态，通用数据对象
export function TaUseAccount(auto: boolean = true) {
	let account = ref(TaDataUser.local.account())
	let relation = ref(TaDataUser.local.relation())
	let userinfo = ref(TaDataUser.local.userinfo())

	onShow(() => auto && loadUser())
	onPullDownRefresh(() => auto && loadUser())

	return { account, relation, userinfo, loadUser }

	function loadUser(): Promise<any> {
		return new Promise((resolve, reject) => {
			if (TaDataUser.local.token()) {
				TaDataUser.userinfo().then((data: any) => {
					account.value = data.account;
					relation.value = data.relation;
					userinfo.value = data.userinfo;
					resolve(data)
				}).catch((ret: any) => {
					TaToast.error(ret.info || ret).then(() => TaDataUser.logout())
				})
			} else {
				reject({ code: 0, info: '请求已被阻止！' })
				TaAbortPosts().then(() => TaDataUser.logout())
			}
		})
	}
}